const express = require("express");
const app = express();
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');

const pager = require("./util/PagerHelper.js");

const loginRoute = require('./routes/LoginRoute');
const adminsRoute = require('./routes/AdminsRoute');
const dormAdminsRoute = require('./routes/DormAdminsRoute');
const dormsRoute = require('./routes/DormsRoute');
const studentsRoute = require('./routes/StudentsRoute');
const menusRoute = require('./routes/MenusRoute');
const absencesRoute =require('./routes/AbsencesRoute')
// 1. 导入用于生成 JWT 字符串的包
const jwt = require("jsonwebtoken");
// 2. 导入用于将客户端发送过来的 JWT 字符串，解析还原成 JSON 对象的包
const expressJWT = require("express-jwt");
// 3. secret 一个密钥字符串
const secretKey = "stu-manager key";
app.locals.jwt = jwt;
app.locals.expressJWT = expressJWT;
app.locals.secretKey = secretKey;

//跨域
const cors = require('cors');
app.use(cors());

//静态资源
app.use(express.static("public"));
//post请求参数中间件
/*
    extended
        true：qs库
        false：使用querystring库
 */
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.json());//vue中的axios发送的是json格式的数据
app.use(cookieParser("stumshop"));
//中间件，统一处理打印及分页插件，必须写在路由之前
app.use((req, res, next) => {
  console.log("req.url:", req.url)
  console.log("req.body:", req.body);
  let {pageNum, pageSize} = req.query;
  if (pageNum && pageNum.trim().length > 0) {
    pager.pageNum = parseInt(pageNum);
  }
  if (pageSize && pageSize.trim().length > 0) {
    pager.pageSize = parseInt(pageSize);
  }

  next();
});
app.use(expressJWT({secret: secretKey, algorithms: ['HS256']}).unless({path: ["/api/login.do","/api/logout.do"]}));
// 登录拦截
// app.all("/*", (req, res, next) => {
//   if (req.session.loginBean) {
//     //登录过
//     console.log("登录过");
//     next();
//   } else {
//     //白名单
//     let whiteUrls = ["/", "/login.html", "/login.do"];
//     if (whiteUrls.some(value => req.path.endsWith(value))) {
//       next();
//     } else {
//       console.log("没有登录过");
//       res.redirect("/login.html");
//     }
//   }
// });
//路由，必须在bodyParser后面
app.use('/api', loginRoute);
app.use('/api/admins', adminsRoute);
app.use('/api/dormAdmins', dormAdminsRoute);
app.use('/api/dorms', dormsRoute);
app.use('/api/students', studentsRoute);
app.use('/api/menus',menusRoute);
app.use('/api/absence',absencesRoute);
app.use(function (err, req, res, next) {
  console.error("错误信息：", err);
  // res.json(err);
  // if (err.name === 'UnauthorizedError') {
  //   return res.status(401).send('invalid token')
  // }

  res.send(err);
})

const port = 8081;
//启动服务，监听端口号
app.listen(port, () => console.log(`服务启动成功，http://localhost:${port}`));

module.exports = app;